<script setup lang="ts">
import { reactive, ref, watch, computed } from 'vue'
import { ElMessage, type FormRules } from 'element-plus'
import { getAntiqueInfo } from '@/api/interface/antique'
import { hasSpaceWithStartAndEnd } from '@/utils/validate'
import { api as viewerApi } from 'v-viewer'
import { uploadFile } from '@/utils/uploader'
import { Plus } from '@element-plus/icons-vue'
import ImageCard from '@/plugins/stratocirri-plus/components/image-uploader/widgets/ImageCard.vue'
import ModelCard from '@/components/business-components/model-card/ModelCard.vue'
import { getShowRoomList } from '@/api/interface/showroom'

interface Props {
  data?: Record<string, any> | never | null
  status?: any
  showRoomId: any
}

const props = withDefaults(defineProps<Props>(), {
  data: null,
  status: 'add',
  showRoomId: ''
})

const disabled = computed(() => {
  return props.status === 'read'
})

const rooms = ref<any>([])

const getRooms = () => {
  getShowRoomList({}).then((res: any) => {
    res.forEach((v: any) => {
      rooms.value.push({
        label: v.otherName,
        value: v.id
      })
    })

    if (props.status == 'add') {
      if (props.showRoomId) {
        form.showRoomId = props.showRoomId
      } else {
        form.showRoomId = res && res.length ? res[0].id : null
      }
    }
  })
}
getRooms()

const formRef = ref()

const form = reactive<Record<string, any>>({})

const rules = reactive<FormRules>({
  antiqueName: [
    { required: true, message: '文物名称不能为空!', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value) {
          if (hasSpaceWithStartAndEnd(value)) {
            callback(new Error('文物名称首尾不能有空格!'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  showRoomId: [{ required: true, message: '所属展厅不能为空!', trigger: 'blur' }],
  typeCode: [{ required: true, message: '文物所属展厅不能为空!', trigger: 'change' }],
  antiqueImageList: [{ required: true, message: '文物图片不能为空!', trigger: 'change' }],
  // modelId: [{ required: true, message: '文物3D模型不能为空!', trigger: 'blur' }],
  introduction: [{ required: true, message: '文物简介不能为空!', trigger: 'blur' }]
})

const loading = ref(false)

const customEditorRef = ref()

const defaultContent = ref('[]')

const editorKey = ref(`${new Date().getTime()}`)

watch(defaultContent, () => {
  editorKey.value = `${new Date().getTime()}`
})

const initForm = () => {
  if (props.data) {
    // 编辑
    loading.value = true
    getAntiqueInfo({
      id: props.data.id
    })
      .then((res: any) => {
        Object.keys(res).forEach((key: string) => {
          if (res![key] || res![key] === 0) {
            if (key === 'antiqueImageEntityList') {
              form.antiqueImageList = res![key].map((v: any) => {
                return {
                  url: v.imageUrl,
                  name: v.imageName
                }
              })
            } else if (key === 'modelEntity') {
              form.modelUrl = res![key].modelUrl
              form.modelImg = res![key].modelImg
              form.modelId = res![key].id
            } else {
              form[key] = res![key]
            }
          }
        })
      })
      .finally(() => {
        loading.value = false
      })
  }
}
initForm()

const formatForm = () => {
  return new Promise((resolve, reject) => {
    const result: Record<string, any> = {}
    Object.keys(form).forEach((key: string) => {
      if (key === 'news') {
        result[key] = customEditorRef.value.formatImage(form[key])
      } else {
        result[key] = form[key]
      }
    })
    // 文件上传相关处理
    const oldImgs = form.antiqueImageList.filter((item: any) => item.url.indexOf('blob:') === -1)
    let imgList: any = []
    oldImgs.forEach((item: any) => {
      imgList.push({
        imageName: item.name,
        imageUrl: item.url
      })
    })
    const needUploadImgs = form.antiqueImageList.filter((item: any) => item.url.indexOf('blob:') > -1)
    console.log(needUploadImgs)
    const illegalFiles = needUploadImgs.filter((item: any) => item.raw.size / 1024 / 1024 > 2)
    if (illegalFiles?.length) {
      illegalFiles.forEach((item: any) => {
        let itemIndex = form.antiqueImageList.indexOf(item)
        ElMessage.error(`第${itemIndex + 1}张图片超过2M，请重新选择！`)
      })
      reject(null)
      return
    }
    const files = needUploadImgs.map((item: any) => item.raw)

    if (files?.length) {
      const promises = files.map((file: any) => uploadFile({ file }))
      Promise.all(promises)
        .then((res: any) => {
          res.forEach((item: any) => {
            imgList.push({
              imageName: item.imgName,
              imageUrl: item.imgUrl
            })
          })
          result['antiqueImageList'] = imgList
          resolve(result)
        })
        .catch(() => {
          reject(null)
        })
    } else {
      result['antiqueImageList'] = imgList
      resolve(result)
    }
  })
}

const submitForm = () => {
  return new Promise<any>((resolve) => {
    formRef.value.validate((valid: boolean) => {
      let res: any = null
      if (valid) {
        res = formatForm()
      }
      resolve(res)
    })
  })
}
const imgPreview = (file: any) => {
  viewerApi({
    images: [file.url],
    options: {
      zIndex: 9999
    }
  })
}

//超出限制
const limitFun = () => {
  ElMessage.error('最多上传5张!')
}

const beforeUploadFun = (file: any) => {
  //限制图片大小
  let size = file.size / 1024 / 1024 < 2

  if (!size) {
    ElMessage.error('上传图片的大小不能超过 2M!')
    return false
  } else {
    return true
  }
}

const imageRemove = () => {
  form.modelUrl = ''
  form.modelId = ''
  form.modelImg = ''
}

const handleModelAdd = () => {
  if (disabled.value) return
  dialogModelVisible.value = true
}

const dialogModelVisible = ref(false)
const modelData = ref<any[]>([])
const modelRef = ref()

const handleModelSubmit = () => {
  const selectedModel = modelRef.value.submitForm()
  form.modelUrl = selectedModel.modelUrl
  form.modelImg = selectedModel.url
  form.modelId = selectedModel.id
  dialogModelVisible.value = false
}

const handleModelClose = () => {
  dialogModelVisible.value = false
}

watch(
  () => form.antiqueImageList,
  () => {
    formRef.value.validateField(['antiqueImageList'])
  }
)

defineExpose({
  submitForm
})
</script>

<template>
  <div v-loading="loading" class="form-wrapper">
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top" label-width="160px">
      <el-form-item label="文物名称：" prop="antiqueName">
        <el-input v-model="form.antiqueName" type="text" maxlength="20" placeholder="请输入文物名称" :disabled="disabled" />
      </el-form-item>
      <el-form-item label="文物所属展厅：" prop="showRoomId">
        <el-select v-model="form.showRoomId" placeholder="请选择展馆" style="width: 100%" :disabled="disabled">
          <el-option v-for="item in rooms" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="文物图片(5张以内)：" prop="antiqueImageList">
        <el-upload
          ref="uploadRef"
          v-model:file-list="form.antiqueImageList"
          action=""
          list-type="picture-card"
          :on-preview="imgPreview"
          accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.GIF"
          :limit="5"
          :on-exceed="limitFun"
          :before-upload="beforeUploadFun"
          :multiple="true"
          :auto-upload="false"
          :disabled="disabled"
        >
          <el-icon>
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="选择3D模型：" prop="modelId">
        <div class="model">
          <div v-if="!form.modelId" class="modelId" @click="handleModelAdd">
            <el-icon>
              <Plus />
            </el-icon>
          </div>
          <div v-else>
            <ImageCard :img-url="form.modelImg" :disabled="disabled" @image-remove="imageRemove"></ImageCard>
          </div>
        </div>
      </el-form-item>
      <el-form-item :key="editorKey" label="文物简介：" prop="introduction">
        <el-input v-model="form.introduction" :rows="5" type="textarea" maxlength="500" :disabled="disabled" placeholder="请输入文物简介" />
      </el-form-item>
    </el-form>
  </div>
  <BaseDialog v-model="dialogModelVisible">
    <template #title>选择3D模型</template>
    <template #buttons>
      <el-button type="info" text bg @click="handleModelClose">取消</el-button>
      <el-button type="primary" @click="handleModelSubmit">确认</el-button>
    </template>
    <ModelCard ref="modelRef" :data="modelData"></ModelCard>
  </BaseDialog>
</template>

<style lang="scss" scoped>
.form-wrapper {
  padding-left: 10px;
}
.model {
  .modelId {
    --el-upload-picture-card-size: 148px;
    background-color: var(--el-fill-color-lighter);
    border: 1px dashed var(--el-border-color-darker);
    border-radius: 6px;
    box-sizing: border-box;
    width: var(--el-upload-picture-card-size);
    height: var(--el-upload-picture-card-size);
    cursor: pointer;
    vertical-align: top;
    display: inline-flex;
    justify-content: center;
    align-items: center;

    .el-icon {
      font-size: 28px;
      color: var(--el-text-color-secondary);
    }
  }

  .modelId:hover {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
  }
}
</style>
